var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require("fs");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/brushdb");
var db = mongoose.connection;
var multer = require("multer");
// 数据库连接
var ObjectID = require('mongodb').ObjectID;
db.on('error',()=>{console.log("连接失败")})
db.on('open',()=>{console.log("连接成功")})


//视图重复使用激活码的用户
var WantRepUsersSchema = mongoose.Schema({
    badactcode:{type:String},
    ipaddress:{type:String},
    platform:{type:String},
    ctime:{type:Date,default:Date.now()},
});

//危险用户
var DangerUsersSchema = mongoose.Schema({
    badactcode:{type:String},
    ipaddress:{type:String},
    platform:{type:String},
    ctime:{type:Date,default:Date.now()},
});
//Active激活码列表
var ActiveCodeSchema = mongoose.Schema({
    actcode:{type:String}
});

//Active激动的用户列表
var ActiveUserSchema = mongoose.Schema({
    actcode:{type:String},
    ipaddress:{type:String},
    ctime:{type:Date,default:Date.now()},
});

//用户表
var UsersBrushSchema = mongoose.Schema({
    actcode:{type:String},
    ipaddress:{type:String},
    url:{type:String},
    brushs:{type:String},
    ctime:{type:Date,default:Date.now()},
});

var BrushInfosSchema = mongoose.Schema({
    actcode: {type:String},
    ipaddress:{type:String},
    url:{type:String},
    comments: {type:String}
});

var RepActUsers  =  mongoose.model('repactusers',WantRepUsersSchema,"repactusers"); //商品
var DangerUsers  =  mongoose.model('dangerusers',DangerUsersSchema,"dangerusers"); //商品
var ActiveCodes  = mongoose.model('activecodes',ActiveCodeSchema,"activecodes"); //商品
var ActiveUsers  = mongoose.model('activeusers',ActiveUserSchema,"activeusers"); //商品
var UsersBrushs  = mongoose.model('userbrush',UsersBrushSchema,"userbrushs");  //用户
var BrushInfos   = mongoose.model('brushinfo',BrushInfosSchema,"brushinfos"); //商品

var app = express();
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {

        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});
app.listen(8017);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'public/upload')));
//登录


app.post("/to_active_brush",function (req,res) {

    let actcode   = req.body.actcode;
    let ipaddress = req.body.ipaddress;
    let platform  = req.body.platform;

    if(actcode != "" && actcode.length >= 20){

        ActiveCodes.findOne({actcode:actcode},function (err,doc) {

            if(err){

                res.json({status:0});
            }else{
                if(doc == null || doc == {}){
                    console.log("激活失败,不存在该激活码！！！！");
                    res.json({status:0});

                    //记录异常信息
                    DangerUsers.create({badactcode:actcode,ipaddress:ipaddress,platform:platform},function (err,doc2) {
                        if(!err){
                            console.log("save the danger user data ok!");
                        }
                    });
                }else{
                    console.log("激活成功");

                    ActiveUsers.findOne({ipaddress:ipaddress},function (err,doc3) {

                        if(err){
                            res.json({status:0});
                        }else{
                            if(doc3 == null || doc3 == {}){
                                //可以激活
                                ActiveUsers.create({ipaddress:ipaddress,actcode:actcode},function (err,doc5) {

                                    if(err){
                                        res.json({status:0});
                                    }else{
                                        res.json({status:0,data:doc5});
                                    }
                                });
                            }else{
                                //尝试重复激活
                                RepActUsers.create({ipaddress:ipaddress,actcode:actcode,platform:platform},function (req,doc4) {
                                    if(!err){
                                        console.log("save the rep user data ok!!");
                                        res.json({status:-1});
                                    }
                                });
                            }
                        }
                    });

                }
            }
        });
    }
});

app.post("/get_brush_actcode",function (req,res) {

    let ipaddress = req.body.ipaddress;
    ActiveUsers.findOne({ipaddress:ipaddress},function (err,doc) {

        if(err){
            res.json({status:0});
        }else{
            res.json({status:1,data:doc});
        }
    });
});


app.post("/get_all_rep_user",function (req,res) {
    let truely = "zjl-mmn";
    let check  = req.body.check;
    if(truely == check){
        RepActUsers.find({},function (err,doc) {

            if(err){
                res.json({status:0});
            }else{
                res.json({status:1,data:doc});
            }
        });
    }
})


app.post("/get_all_act_user",function (req,res) {
    let truely = "zjl-mmn";
    let check  = req.body.check;
    if(truely == check){
        ActiveUsers.find({},function (err,doc) {

            if(err){
                res.json({status:0});
            }else{
                res.json({status:1,data:doc});
            }
        });
    }
});


app.post("/get_all_danger_user",function (req,res) {
    let truely = "zjl-mmn";
    let check  = req.body.check;
    if(truely == check){
        DangerUsers.find({},function (err,doc) {

            if(err){
                res.json({status:0});
            }else{
                res.json({status:1,data:doc});
            }
        });
    }
});


app.post("/get_all_act_code",function (req,res) {
    let truely = "zjl-mmn";
    let check  = req.body.check;
    if(truely == check){
        ActiveCodes.find({},function (err,doc) {

            if(err){
                res.json({status:0});
            }else{
                res.json({status:1,data:doc});
            }
        });
    }
});

app.get("/add_root_act_code",function (req,res) {

    let truely  = "zjl-mmn";
    let check   = req.query.check;
    let actcode = req.query.actcode;
    if(truely == check) {

        ActiveCodes.findOne({actcode:actcode},function (err,doc) {

            if(err){
                res.json({status:0});
            }else{
                 if(doc == null || doc == {}){

                     ActiveCodes.create({actcode:actcode},function (err,doc2) {
                         if(err){
                             res.json({status:0});
                         }else{
                             res.json({status:1,data:doc2});
                         }
                     });
                 }else{
                     res.json({status:0,data:"已经存在这个激活码了"});
                 }
            }
        });
    }
});


app.post("/save_brush",function (req,res) {
   let actcode   = req.body.actcode;
   let url       = req.body.url;
   let brushs    = req.body.brushs;
   let ipaddress = req.body.ipaddress;


   UsersBrushs.findOne({url:url,ipaddress:ipaddress},function (err,data) {
        if(!err){
                if(data == {} || data == null){   //没有这个条目

                   UsersBrushs.create({actcode:actcode,url:url,brushs:brushs,ipaddress:ipaddress},function (err,doc) {
                       if(!err){
                           console.log("添加brush 数据成功~~~");
                           res.json({status:1});
                       }else{
                           console.log("添加brush 数据失败~~~~！！！！");
                           res.json({status:0});
                       }
                   });
                }else{
                      //追加
                      UsersBrushs.updateOne({url:url,ipaddress:ipaddress},{brushs:brushs},function (err,doc2) {

                          if(err){
                              res.json({status:0});
                          }else{
                              res.json({status:1});
                          }
                      });
                }
            }
    });
});


app.post("/get_brush_data",function (req,res) {

    let url = req.body.url;
    let ipaddress = req.body.ipaddress;
    console.log(url);
    console.log(ipaddress);
    UsersBrushs.findOne({url:url,ipaddress:ipaddress},function (err,doc) {

        if(err){
            console.log("获取brush 数据失败~~~~！！！！");
            res.json({status:0});
        }else{

            if(doc==null || doc == {}){
                res.json({status:0});
            }else{
                res.json({status:1,data:doc});
            }
        }
    });
});



app.post("/save_brush_comment",function (req,res) {
    let comments = req.body.comments;
    let url      = req.body.url;
    let actcode  = req.body.actcode;
    let ipaddress = req.body.ipaddress;
    BrushInfos.findOne({url:url,ipaddress:ipaddress},function (err,data) {

        if(!err){
            //无数据+
            if(data == {} || data == null){

                BrushInfos.create({ipaddress:ipaddress,actcode:actcode,url:url,comments:comments},function (err,doc1) {
                    if(err){
                        res.json({status:0});
                    }else{
                        res.json({status:1});
                    }
                });
            }else{
                //更新数据
                BrushInfos.updateOne({url:url,ipaddress:ipaddress},{comments:comments},function (err,doc2) {
                    if(err){
                        res.json({status:0});
                    }else{
                        res.json({status:1});
                    }
                });
            }
        }
    });
});

app.post("/get_brush_comment",function (req,res) {
    let url = req.body.url;
    let ipaddress = req.body.ipaddress;
    BrushInfos.findOne({url:url,ipaddress:ipaddress},function (err,doc) {

        if(err){
            res.json({status:0});
        }else{
            if(doc == {} || doc == null){
                res.json({status:0});
            }else{
                res.json({status:1,data:doc});
            }
        }
    });
});

module.exports = app;
